import asyncio
import json
import time

import websockets
from src.event import Notice_event
from src.event.msg_event import Msg_event
from src.utrls import DefUtrl
from src.Init import ws_address


async def start():
    while True:
        try:
            print("正在连接ws端....")
            await connect_to_ws()
        except Exception as error:
            print(f"出现错误：error={error}")
            DefUtrl.voice("连接出现错误！")
            print("等待2秒后继续连接...")
            time.sleep(1)


async def connect_to_ws():
    async with websockets.connect(ws_address) as w:
        print("=" * 10 + "连接成功！" + "=" * 10)
        while True:
            data: dict = json.loads(await w.recv())
            message_type = data.get("message_type", "")
            if not message_type == "":
                await Msg_event.run(data, message_type)  # 消息事件
                continue
            notice_type = data.get("notice_type", "")
            if not notice_type == "":
                await Notice_event.run(data, notice_type)  # 通知事件


asyncio.run(start())
